package com.atguigu.gmall.list.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.list.rep.GoodsRep;
import com.atguigu.gmall.list.service.SearchService;
import com.atguigu.gmall.model.list.*;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    //  ElasticsearchRestTemplate
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //  这个接口中有操作esCRUD 方法。

    @Autowired
    private GoodsRep goodsRep;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Override
    public void upperGoods(Long skuId) {
        //  创建goods 对象
        Goods goods = new Goods();
        //  多线程查询商品数据进行上架操作！
        //  判断使用有返回值，没有返回值！
        CompletableFuture<SkuInfo> skuInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            //  查询skuInfo
            SkuInfo skuInfo = this.productFeignClient.getSkuInfo(skuId);
            goods.setId(skuId);
            //  商品价格  skuInfo.getPrice() --> 可能来自于缓存; 可能会在某一瞬间产生数据不一致的问题！
            //  goods.setPrice(skuInfo.getPrice().doubleValue());
            //  直接查询数据库
            goods.setPrice(this.productFeignClient.getSkuPrice(skuId).doubleValue());
            goods.setTitle(skuInfo.getSkuName());
            goods.setDefaultImg(skuInfo.getSkuDefaultImg());
            goods.setCreateTime(new Date());
            return skuInfo;
        });

        //  品牌数据：
        CompletableFuture<Void> tmCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo -> {
            //  查询品牌数据
            BaseTrademark trademark = productFeignClient.getTrademark(skuInfo.getTmId());
            goods.setTmId(trademark.getId());
            goods.setTmName(trademark.getTmName());
            goods.setTmLogoUrl(trademark.getLogoUrl());
        });

        //  获取分类数据
        CompletableFuture<Void> cateCompletableFuture = skuInfoCompletableFuture.thenAcceptAsync(skuInfo -> {
            BaseCategoryView categoryView = this.productFeignClient.getCategoryView(skuInfo.getCategory3Id());
            goods.setCategory1Id(categoryView.getCategory1Id());
            goods.setCategory2Id(categoryView.getCategory2Id());
            goods.setCategory3Id(categoryView.getCategory3Id());
            goods.setCategory1Name(categoryView.getCategory1Name());
            goods.setCategory2Name(categoryView.getCategory2Name());
            goods.setCategory3Name(categoryView.getCategory3Name());
        });
        //  商品详情将根据skuId 获取平台属性以及平台属性值
        CompletableFuture<Void> attrCompletableFuture = CompletableFuture.runAsync(() -> {
            //  private List<SearchAttr> attrs;
            List<BaseAttrInfo> attrList = this.productFeignClient.getAttrList(skuId);
            List<SearchAttr> searchAttrList = attrList.stream().map(baseAttrInfo -> {
                SearchAttr searchAttr = new SearchAttr();
                searchAttr.setAttrId(baseAttrInfo.getId());
                searchAttr.setAttrName(baseAttrInfo.getAttrName());
                //  根据skuId 进行商品上架 skuId = 22
                searchAttr.setAttrValue(baseAttrInfo.getAttrValueList().get(0).getValueName());
                return searchAttr;
            }).collect(Collectors.toList());
            //  赋值
            goods.setAttrs(searchAttrList);
        });

        //  多任务组合：
        CompletableFuture.allOf(
                skuInfoCompletableFuture,
                cateCompletableFuture,
                tmCompletableFuture,
                attrCompletableFuture
                ).join();
        //  保存
        goodsRep.save(goods);

    }

    @Override
    public void lowerGoods(Long skuId) {
        goodsRep.deleteById(skuId);
    }

    @Override
    public void incrHotScore(Long skuId) {
        //  借助redis; 分析 String incr/decr key  incrby/decrby key increment Zset-排序 zincrby key 1 skuId
        String key = "hotScore";
        Double score = this.redisTemplate.opsForZSet().incrementScore(key, "skuId:" + skuId, 1);
        //  判断
        if (score%10==0){
            //  更新一次es
            Optional<Goods> optional = goodsRep.findById(skuId);
            Goods goods = optional.get();
            goods.setHotScore(score.longValue());
            this.goodsRep.save(goods);
        }
    }

    @Override
    public SearchResponseVo search(SearchParam searchParam) {
        //  1.  生成dsl语句
        SearchRequest searchRequest = this.buildDsl(searchParam);
        //  2.  执行dsl 语句
        //  SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchResponse searchResponse = null;
        try {
            searchResponse = this.restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //  3.  获取到执行结果转换为SearchResponseVo实体
        SearchResponseVo searchResponseVo = this.parseResult(searchResponse);

        /*
            private Integer pageSize;//每页显示的条数
            private Integer pageNo;//当前页面
            private Long totalPages;// 总页数
        */
        //  每页显示的条数
        searchResponseVo.setPageSize(searchParam.getPageSize());
        //  当前页
        searchResponseVo.setPageNo(searchParam.getPageNo());
        //  总页数 10 3 4   9 3 3
        //  Long totalPages = searchResponseVo.getTotal()%searchParam.getPageSize()==0?searchResponseVo.getTotal()/searchParam.getPageSize():searchResponseVo.getTotal()/searchParam.getPageSize()+1;
        Long totalPages = (searchResponseVo.getTotal() + searchParam.getPageSize() - 1)/searchParam.getPageSize();
        searchResponseVo.setTotalPages(totalPages);
        //  返回数据
        return searchResponseVo;
    }

    /**
     * 封装返回结果集对象
     * @param searchResponse
     * @return
     */
    private SearchResponseVo parseResult(SearchResponse searchResponse) {
        //  创建对象
        SearchResponseVo searchResponseVo = new SearchResponseVo();
        /*
        本质给这个对象属性赋值：
        private List<SearchResponseTmVo> trademarkList;
        private List<SearchResponseAttrVo> attrsList = new ArrayList<>();
        private List<Goods> goodsList = new ArrayList<>();
        private Long total;//总记录数
         */
        SearchHits hits = searchResponse.getHits();
        //  赋值总记录数
        searchResponseVo.setTotal(hits.getTotalHits().value);
        //  获取 goods 列表
        List<Goods> goodsList = new ArrayList<>();
        //  获取商品集合数据添加到 goodsList
        SearchHit[] subHits = hits.getHits();
        //  循环遍历获取数据
        for (SearchHit subHit : subHits) {
            //  获取商品的json 字符串
            String sourceAsString = subHit.getSourceAsString();
            //  将这个json 数据转为 goods
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            //  获取商品的名称： 如果是分词查询，则商品名称必须要高亮;  不能获取 _source 下的title 数据！ highlight 下的title 数据！
            //  判断是否根据关键词查询
            if (subHit.getHighlightFields().get("title")!=null){
                //  说是按照关键词查询的.
                String title = subHit.getHighlightFields().get("title").getFragments()[0].toString();
                //  将高亮的商品名称赋值给title
                goods.setTitle(title);
            }
            //  将goods 添加到集合中.
            goodsList.add(goods);
        }
        //  赋值商品集合列表
        searchResponseVo.setGoodsList(goodsList);
        //  赋值品牌数据 List<SearchResponseTmVo> trademarkList;
        //  获取聚合中的map
        Map<String, Aggregation> aggregationMap = searchResponse.getAggregations().asMap();
        //  tmIdAgg 看做一个key
        ParsedLongTerms tmIdAgg = (ParsedLongTerms) aggregationMap.get("tmIdAgg");
        //  获取品牌集合数据
        List<SearchResponseTmVo> trademarkList = tmIdAgg.getBuckets().stream().map(bucket -> {
            //  声明一个品牌对象
            SearchResponseTmVo searchResponseTmVo = new SearchResponseTmVo();
            //  获取品牌Id
            String tmId = bucket.getKeyAsString();
            searchResponseTmVo.setTmId(Long.parseLong(tmId));
            //  获取品牌名称：
            ParsedStringTerms tmNameAgg = bucket.getAggregations().get("tmNameAgg");
            String tmName = tmNameAgg.getBuckets().get(0).getKeyAsString();
            searchResponseTmVo.setTmName(tmName);
            //  获取品牌logo
            ParsedStringTerms tmLogoUrlAgg = bucket.getAggregations().get("tmLogoUrlAgg");
            String tmLogoUrl = tmLogoUrlAgg.getBuckets().get(0).getKeyAsString();
            searchResponseTmVo.setTmLogoUrl(tmLogoUrl);
            //  返回当个品牌对象
            return searchResponseTmVo;
        }).collect(Collectors.toList());

        //  赋值品牌集合对象
        searchResponseVo.setTrademarkList(trademarkList);

        //  获取平台属性数据：attrs 数据类型是nested.
        ParsedNested attrsAgg = (ParsedNested) aggregationMap.get("attrsAgg");
        //  根据key 来获取平台属性聚合
        ParsedLongTerms attrIdAgg = attrsAgg.getAggregations().get("attrIdAgg");
        List<SearchResponseAttrVo> attrVoList = attrIdAgg.getBuckets().stream().map(bucket -> {
            //  创建对象
            SearchResponseAttrVo searchResponseAttrVo = new SearchResponseAttrVo();
            //  获取平台属性Id
            String attrId = bucket.getKeyAsString();
            searchResponseAttrVo.setAttrId(Long.parseLong(attrId));
            //  获取平台属性名
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attrNameAgg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            searchResponseAttrVo.setAttrName(attrName);

            //  获取平台属性值名称
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
            List<String> valueNameList = attrValueAgg.getBuckets().stream().map(bucket1 -> bucket1.getKeyAsString()).collect(Collectors.toList());
            //  将平台属性值集合放入对象中。
            searchResponseAttrVo.setAttrValueList(valueNameList);
            //  返回平台属性对象
            return searchResponseAttrVo;
        }).collect(Collectors.toList());
        //  赋值平台属性集合
        searchResponseVo.setAttrsList(attrVoList);
        return searchResponseVo;
    }

    /**
     * 生成dsl 语句
     * @param searchParam
     * @return
     */
    private SearchRequest buildDsl(SearchParam searchParam) {
        //  创建一个查询器： { query sort form size ... }
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //  bool
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //  判断用户是否根据分类Id 查询！ 分类Id 查询入口
        if (!StringUtils.isEmpty(searchParam.getCategory1Id())){
            //  filter -- term
            boolQueryBuilder.filter(QueryBuilders.termQuery("category1Id",searchParam.getCategory1Id()));
        }
        if (!StringUtils.isEmpty(searchParam.getCategory2Id())){
            //  filter -- term
            boolQueryBuilder.filter(QueryBuilders.termQuery("category2Id",searchParam.getCategory2Id()));
        }
        if (!StringUtils.isEmpty(searchParam.getCategory3Id())){
            //  filter -- term
            boolQueryBuilder.filter(QueryBuilders.termQuery("category3Id",searchParam.getCategory3Id()));
        }
        //  根据关键词查询：keyword
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            //  must --- match
            boolQueryBuilder.must(QueryBuilders.matchQuery("title",searchParam.getKeyword()).operator(Operator.AND));
            //  无检索不高亮！
            //  设置高亮的字段以及格式
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("title");
            highlightBuilder.preTags("<span style=color:red>");
            highlightBuilder.postTags("</span>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        //  用户可以通过品牌进行过滤：
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)){
            //  1:小米
            String[] split = trademark.split(":");
            if (split!=null && split.length==2){
                boolQueryBuilder.filter(QueryBuilders.termQuery("tmId", split[0]));
            }
        }

        //  根据平台属性过滤 nested;
        //  props=24:128G:机身内存&props=23:4G:运行内存
        String[] props = searchParam.getProps();
        if (props!=null && props.length>0){
            //  遍历整个数组
            for (String prop : props) {
                //  进行分割获取到内部数据
                String[] split = prop.split(":");
                if (split!=null && split.length==3){
                    //  创建内部bool
                    BoolQueryBuilder innerBoolQueryBuilder = QueryBuilders.boolQuery();
                    //  获取到平台属性Id
                    innerBoolQueryBuilder.filter(QueryBuilders.termQuery("attrs.attrId",split[0]));
                    //  获取到平台属性值
                    innerBoolQueryBuilder.filter(QueryBuilders.termQuery("attrs.attrValue",split[1]));
                    //  将内部的bool 传递给外层bool
                    //  filter--nested
                    boolQueryBuilder.filter(QueryBuilders.nestedQuery("attrs",innerBoolQueryBuilder, ScoreMode.None));
                }
            }
        }

        //  设置分页：
        int from = (searchParam.getPageNo()-1)*searchParam.getPageSize();
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(searchParam.getPageSize());

        //  设置排序：
        //  order=1:asc order=1:desc order=2:asc order=2:desc  1:表示综合-hotScore 2:表示价格price
        //  获取到用户排序规则
        String order = searchParam.getOrder();
        if (!StringUtils.isEmpty(order)){
            //  分割数据
            String[] split = order.split(":");
            if (split!=null && split.length==2){
                //  声明一个排序字段
                String orderField = "";
                switch (split[0]){
                    case "1":
                        orderField = "hotScore";
                        break;
                    case "2":
                        orderField = "price";
                        break;
                }
                //  设置排序字段与规则
                searchSourceBuilder.sort(orderField,"asc".equals(split[1])?SortOrder.ASC:SortOrder.DESC);
            }
        }else {
            //  设置排序字段与规则
            searchSourceBuilder.sort("hotScore",SortOrder.DESC);
        }
        //  query --> bool
        searchSourceBuilder.query(boolQueryBuilder);
        //  品牌聚合
        searchSourceBuilder.aggregation(AggregationBuilders.terms("tmIdAgg").field("tmId")
                        .subAggregation(AggregationBuilders.terms("tmNameAgg").field("tmName"))
                        .subAggregation(AggregationBuilders.terms("tmLogoUrlAgg").field("tmLogoUrl")));

        //  平台属性聚合：
        searchSourceBuilder.aggregation(AggregationBuilders.nested("attrsAgg","attrs")
                .subAggregation(AggregationBuilders.terms("attrIdAgg").field("attrs.attrId")
                        .subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName"))
                        .subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue"))));

        //  查询：GET /goods/_search
        SearchRequest searchRequest = new SearchRequest("goods");
        //  将生成的dsl 语句赋值给对象
        searchRequest.source(searchSourceBuilder);
        searchSourceBuilder.fetchSource(new String[] {"id", "defaultImg","title","price"},null);
        //  打印dsl 语句
        System.out.println("dsl:\t"+searchSourceBuilder.toString());
        //  返回请求对象
        return searchRequest;
    }
}
